"""
TypedDict 实践示例：数据处理管道与 API 集成
演示 TypedDict 在实际项目中的应用
"""
from typing import TypedDict, List, Dict, Optional, Generator, Any
import json
from datetime import datetime
import time
from functools import wraps
import random

# ============= 数据模型定义 =============

class UserData(TypedDict):
    """用户基础数据结构"""
    user_id: int
    username: str
    email: str
    active: bool


class UserStats(TypedDict):
    """用户统计数据"""
    login_count: int
    last_login: float
    session_time: List[float]


class UserProfile(TypedDict):
    """完整的用户资料"""
    basic: UserData
    stats: UserStats
    preferences: Dict[str, Any]
    tags: Optional[List[str]]


class AnalysisResult(TypedDict):
    """分析结果数据结构"""
    timestamp: float
    user_count: int
    active_ratio: float
    avg_session_time: float
    user_segments: Dict[str, int]


class APIResponse(TypedDict):
    """API 响应格式"""
    status: str
    code: int
    data: Any
    message: str


# ============= 类型验证装饰器 =============

def validate_typeddict(cls):
    """验证数据是否符合 TypedDict 定义的结构"""
    def decorator(func):
        @wraps(func)
        def wrapper(data, *args, **kwargs):
            # 简单验证，实际项目中可能需要更复杂的验证逻辑
            if not isinstance(data, dict):
                raise TypeError(f"数据必须是字典类型，收到: {type(data)}")
            
            # 检查必需字段
            for field in cls.__annotations__:
                if field not in data:
                    raise ValueError(f"缺少必需字段: {field}")
            
            return func(data, *args, **kwargs)
        return wrapper
    return decorator


# ============= 模拟 API 服务 =============

def fetch_user_data() -> Generator[UserData, None, None]:
    """模拟从 API 获取用户数据"""
    # 模拟数据
    users = [
        {
            "user_id": 1001,
            "username": "张三",
            "email": "zhangsan@example.com",
            "active": True
        },
        {
            "user_id": 1002,
            "username": "李四",
            "email": "lisi@example.com",
            "active": False
        },
        {
            "user_id": 1003,
            "username": "王五",
            "email": "wangwu@example.com",
            "active": True
        }
    ]
    
    for user in users:
        # 模拟网络延迟
        time.sleep(0.1)
        yield user


def fetch_user_stats(user_id: int) -> UserStats:
    """模拟获取用户统计数据"""
    # 模拟数据生成
    stats: UserStats = {
        "login_count": random.randint(1, 100),
        "last_login": time.time() - random.randint(0, 86400),
        "session_time": [random.random() * 60 for _ in range(5)]
    }
    return stats


# ============= 数据处理管道 =============

@validate_typeddict(UserData)
def enrich_user_data(user_data: UserData) -> UserProfile:
    """丰富用户数据，添加统计信息和偏好设置"""
    user_id = user_data["user_id"]
    stats = fetch_user_stats(user_id)
    
    # 构建完整用户资料
    profile: UserProfile = {
        "basic": user_data,
        "stats": stats,
        "preferences": {
            "theme": "dark" if random.random() > 0.5 else "light",
            "notifications": True,
            "language": "zh-CN"
        },
        "tags": ["新用户"] if stats["login_count"] < 5 else ["活跃用户"]
    }
    
    return profile


def analyze_user_profiles(profiles: List[UserProfile]) -> AnalysisResult:
    """分析用户资料数据"""
    active_users = sum(1 for p in profiles if p["basic"]["active"])
    total_users = len(profiles)
    
    # 计算平均会话时间
    all_sessions = [session for p in profiles for session in p["stats"]["session_time"]]
    avg_session = sum(all_sessions) / len(all_sessions) if all_sessions else 0
    
    # 用户分类统计
    segments = {}
    for profile in profiles:
        for tag in profile.get("tags", []):
            segments[tag] = segments.get(tag, 0) + 1
    
    # 构建分析结果
    result: AnalysisResult = {
        "timestamp": time.time(),
        "user_count": total_users,
        "active_ratio": active_users / total_users if total_users else 0,
        "avg_session_time": avg_session,
        "user_segments": segments
    }
    
    return result


def format_api_response(data: Any, success: bool = True) -> APIResponse:
    """格式化 API 响应"""
    response: APIResponse = {
        "status": "success" if success else "error",
        "code": 200 if success else 500,
        "data": data,
        "message": "操作成功" if success else "处理失败"
    }
    return response


# ============= 主程序 =============

def main():
    print("开始数据处理流程...")
    
    try:
        # 1. 获取原始用户数据
        print("\n1. 从API获取用户数据")
        user_data_list = list(fetch_user_data())
        print(f"获取到 {len(user_data_list)} 条用户记录")
        
        # 2. 数据丰富处理
        print("\n2. 丰富用户数据")
        user_profiles = [enrich_user_data(user) for user in user_data_list]
        print("用户数据丰富完成")
        
        # 3. 数据分析
        print("\n3. 分析用户数据")
        analysis = analyze_user_profiles(user_profiles)
        print("数据分析完成")
        
        # 4. 格式化API响应
        print("\n4. 生成API响应")
        api_response = format_api_response(analysis)
        
        # 5. 输出结果
        print("\n=== 处理结果 ===")
        print(json.dumps(api_response, indent=2, ensure_ascii=False))
        
    except Exception as e:
        print(f"处理过程中出错: {e}")
        api_response = format_api_response({"error": str(e)}, success=False)
        print(json.dumps(api_response, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()